import Message from "./message";
import Subject from './subject';

class Network extends Subject{
    constructor(){
        super();
        this.connected = false;
        this.targetAddress = "";
        this.waittingList = [];
    }
    connect(){ 
        this.ws = new WebSocket( this.targetAddress );
        this.ws.onopen = this.onOpen.bind(this);
        this.ws.onclose = this.onClose.bind(this);
        this.ws.onmessage = this.onMessage.bind(this);
        this.ws.onerror = this.onError.bind(this);
    }
    onOpen( evt ){
        evt;
        this.connected = true;
        this.emit("onOpen");
    }
    onClose( evt ) {
        evt;
        this.connected = false;
        this.emit("onClose");
    }
    onError( evt ) {
        evt;
        this.emit("onError");
    }
    onMessage( evt ) {
        let msg = new Message.createFromJson( evt.data );
        for( var key in Message.Type) {
            if( msg.type == Message.Type[key] ) {
                console.log( "[c<-m] onMessage", key, msg );
                
            }
        }
        if( this.waittingList.length >0 ) {
            for(let i=0;i<this.waittingList.length;i++){
                let wl = this.waittingList[i];
                if( wl[0] == msg.type ) {
                    this.waittingList.splice(i,1);
                    wl[1](msg);
                    break;
                }
            }
        }

        this.emit("onMessage", msg );
    }
    sendMessage( msg ) {
        for( var key in Message.Type) {
            if( msg.type == Message.Type[key] ) {
                console.log( "[c->m] sendMessage:", key,  msg );
            }
        }
        this.ws.send( JSON.stringify( msg ) );
    }

    waitForMessage( type, thenCallback ) {
        this.waittingList.push([type,thenCallback]);
    }
}

var network = new Network();
export default network;